import { SearchAction, SearchInitType } from '@/types/store'
import { getLocalHistories } from '@/utils/storage'

const initValue: SearchInitType = {
  suggestion: [],
  history: getLocalHistories(),
  resultsObj: {
    page: 0,
    per_page: 10,
    results: [],
    total_count: -1,
  },
}
export default function profile(
  prevState = initValue,
  action: SearchAction
): SearchInitType {
  switch (action.type) {
    case 'search/getSuggestionList':
      return {
        ...prevState,
        suggestion: action.payload,
      }
    case 'search/saveHistory':
      return {
        ...prevState,
        history: action.payload,
      }
    case 'search/getResults':
      const oldResults = prevState.resultsObj.results
      return {
        ...prevState,
        resultsObj: {
          ...action.payload,
          results: [...oldResults, ...action.payload.results],
        },
      }
    case 'search/clearResObj':
      return {
        ...prevState,
        resultsObj: {
          page: 0,
          per_page: 10,
          results: [],
          total_count: -1,
        },
      }

    default:
      return prevState
  }
}
